package cn.edu.zstu.qingzhu.qingzhushop.controller;

import cn.edu.zstu.qingzhu.qingzhushop.common.ResponseBeanMessage;
import cn.edu.zstu.qingzhu.qingzhushop.entity.*;
import cn.edu.zstu.qingzhu.qingzhushop.service.IOrderService;
import cn.edu.zstu.qingzhu.qingzhushop.service.IShoppingCartService;
import cn.edu.zstu.qingzhu.qingzhushop.service.IUserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单相关功能控制器
 *
 * @author ShenTuZhiGang
 * @version 1.0.0
 * @date 2020-11-08 15:33
 */
@RestController
@RequestMapping("/order")
@CrossOrigin(origins={"*"}, methods={RequestMethod.GET, RequestMethod.POST,RequestMethod.PUT,RequestMethod.DELETE})
@Api(tags = "订单接口")
public class OrderController {

    @Autowired
    IUserService iUserService;

    @Autowired
    private IOrderService iOrderService;

    @Autowired
    private IShoppingCartService iShoppingCartService;

    @Autowired
    ObjectMapper objectMapper;

    /**
     * 订单详情
     * @param orderNo 订单编号
     * @param authentication Spring Security的用户认证信息
     * @return 订单详情
     */
    @GetMapping("/detail/{orderNo}")
    public ResponseBean orderDetailPage(@PathVariable("orderNo") String orderNo,
                                  Authentication authentication) {
        AuthenticationUser user = (AuthenticationUser) authentication.getPrincipal();
        OrderDetail orderDetail = iOrderService.getOrderDetailByOrderNo(orderNo, user.getId());
        if (orderDetail == null) {
            return ResponseBean.error();
        }
        return ResponseBean.success("orderDetail", orderDetail);
    }

    /**
     * 订单列表
     *
     * 分页查询
     *
     * @param page 页数
     * @param size 每页数量
     * @param authentication Spring Security的用户认证信息
     * @return 订单列表
     */
    @GetMapping("/orders")
    public Object orderListPage(@ApiParam(name = "page",value = "页数") @RequestParam(defaultValue = "1") Integer page,
                                @ApiParam(name = "size",value = "记录数")@RequestParam(defaultValue = "10") Integer size,
                                Authentication authentication) {
        AuthenticationUser user = (AuthenticationUser) authentication.getPrincipal();
        return iOrderService.listOrderByUserId(user.getId(), page,size);
    }


    /**
     * 订单列表
     *
     * 分页查询
     *
     * @param page 页数
     * @param size 每页数量
     * @param id 用户ID
     * @return 订单列表
     */
    @GetMapping("/list")
    public Object orderList(@ApiParam(name = "page",value = "页数")
                                @RequestParam(defaultValue = "1") Integer page,
                                @ApiParam(name = "size",value = "记录数")
                                @RequestParam(defaultValue = "10") Integer size,
                                @PathVariable("id") Integer id) {

        return iOrderService.listOrderByUserId(id, page,size);
    }

    /**
     * 新建订单
     * @param authentication Spring Security的用户认证信息
     * @return 订单详情
     */
    @GetMapping("/save")
    public ResponseBean saveOrder(Authentication authentication) {
        AuthenticationUser user = (AuthenticationUser) authentication.getPrincipal();
        List<ShoppingCart> shoppingCartList = iShoppingCartService.listOrderByUserId(user.getId());
        if (StringUtils.isEmpty(user.getAddress().trim())) {
            //无收货地址
            return ResponseBean.error(ResponseBeanMessage.NULL_ADDRESS_ERROR);
        }
        if (CollectionUtils.isEmpty(shoppingCartList)) {
            //购物车中无数据则跳转至错误页
            return ResponseBean.error(ResponseBeanMessage.SHOPPING_ITEM_ERROR);
        }
        //保存订单并返回订单号
        return ResponseBean.success(iOrderService.saveOrder(user, shoppingCartList));
    }

    /**
     * 新建订单
     * @return 订单详情
     */
    @PostMapping("/submit")
    public ResponseBean submitOrder(@RequestBody SubmitOrderDTO dto) throws JsonProcessingException {
        User user = iUserService.getById(dto.getUid());
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        List<Integer> list = objectMapper.readValue(dto.getGoods(), new TypeReference<List<Integer>>(){/**/});
        if (StringUtils.isEmpty(user.getAddress().trim())) {
            //无收货地址
            return ResponseBean.error(ResponseBeanMessage.NULL_ADDRESS_ERROR);
        }
        if (list.size() == 0) {
            //购物车中无数据则跳转至错误页
            return ResponseBean.error(ResponseBeanMessage.SHOPPING_ITEM_ERROR);
        }

        Order order = new Order();
        order.setAmount(dto.getAmount());
        order.setTotalnumber(list.size());
        order.setStatus("未付款");
        order.setAddress(dto.getAddress()==null?user.getAddress():dto.getAddress());
        order.setCustomerId(user.getId());
        order.setEmployeeId(0);
        order.setMessage(dto.getMessage());
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        try{
            //保存订单并返回订单号
            return ResponseBean.success("订单编号",iOrderService.submitOrder(order,list));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBean.error (e.getMessage());
        }
    }


    /**
     * 取消订单
     * @param orderNo 订单编号
     * @param id 用户id
     * @param authentication Spring Security的用户认证信息
     * @return 订单详情
     */
    @PutMapping("/orders/{orderNo}/cancel")
    @ResponseBody
    public ResponseBean cancelOrder(@PathVariable("orderNo") String orderNo, @PathVariable("id") Integer id,Authentication authentication) {
        AuthenticationUser user = (AuthenticationUser) authentication.getPrincipal();
        user.setId(id);
        String cancelOrderResponseBean = iOrderService.cancelOrder(orderNo, user.getId());
        if (ResponseBeanMessage.SUCCESS.equals(cancelOrderResponseBean)) {
            return ResponseBean.success();
        } else {
            return ResponseBean.error(cancelOrderResponseBean);
        }
    }

    /**
     * 关闭订单
     * @param orderNo 订单编号
     * @param id 用户id
     * @param authentication Spring Security的用户认证信息
     * @return 订单详情
     */
    @PutMapping("/orders/{orderNo}/finish")
    @ResponseBody
    public ResponseBean finishOrder(@PathVariable("orderNo") String orderNo, @PathVariable("id") Integer id,Authentication authentication) {
        AuthenticationUser user = (AuthenticationUser) authentication.getPrincipal();
        user.setId(id);
        String finishOrderResponseBean = iOrderService.finishOrder(orderNo, user.getId());
        if (ResponseBeanMessage.SUCCESS.equals(finishOrderResponseBean)) {
            return ResponseBean.success();
        } else {
            return ResponseBean.error(finishOrderResponseBean);
        }
    }

    /**
     * 选择支付类型
     * @param orderNo 订单编号
     * @param authentication Spring Security的用户认证信息
     * @return 成功
     */
    @GetMapping("/selectPayType")
    public ResponseBean selectPayType( @RequestParam("orderNo") String orderNo, Authentication authentication) {
        AuthenticationUser user = (AuthenticationUser) authentication.getPrincipal();
        return ResponseBean.success();
    }

    /**
     * 跳转支付页
     * @param orderNo 订单编号
     * @param authentication Spring Security的用户认证信息
     * @param payType 支付类型
     * @return 成功
     */
    @GetMapping("/payPage")
    public ResponseBean payOrder( @RequestParam("orderNo") String orderNo, Authentication authentication, @RequestParam("payType") int payType) {
        AuthenticationUser user = (AuthenticationUser) authentication.getPrincipal();
        return ResponseBean.success();
    }

    /**
     * 支付成功回调
     * @param orderNo 订单编号
     * @return 成功
     */
    @GetMapping("/paySuccess")
    @ResponseBody
    public ResponseBean paySuccess(@RequestParam("orderNo") Integer orderNo) throws Exception {
        int msg = iOrderService.paySuccess(orderNo);
        if (msg==0){
            return ResponseBean.error();
        }else if(msg==1){
            return ResponseBean.success("支付成功");
        }else if (msg==3){
            return ResponseBean.error("订单超时已取消");
        }else{
            return ResponseBean.error("请勿重复支付");
        }
    }

}
